#ifndef NETWORKHANDLER_H
#define NETWORKHANDLER_H

//Note: NetworkHandler is a slightly modified version of the BlockingClient from the Last.FM ScrobSubmitter API.

#include <winsock2.h>
#include <string>


/**
 *   Client for sending and receiving commands down a WinSock2 Socket
 */


class NetworkHandler
{
public:
	/**
	* A class for handling network exceptions
	*/
	class NetworkException : public std::logic_error {
		public:
			NetworkException(const std::string& sMsg) : logic_error(sMsg) { }
		};

	/**
	* Constructor 
	*/
	NetworkHandler();

	/**
	* Destructor
	*/
	~NetworkHandler();


	/**
	* Connect to server
	* @param[in] sHost The host to connnect to.
	* @param[in] nPort The port on the host to connect to.
	*
	* @return The port number connected to.  Port stepping will be used
	*         until the correct port is located
	*/

	unsigned int Connect(const std::string & sHost, u_short nPort);

	/**
	* Send a string down the socket
	* 
	* @param[in] sData The data to be sent.
	*/
	void Send(const std::string & sData);

	/**
	* Recieve a line from the socket
	*
	* @param[out] sData The data received from the connection.
	*/
	void Receive(std::string & sData);

	/**
	* Disconnect gracefully.
	*/
	void Disconnect();

private:
    /**
	* Looks up the IP Address for a given string.
	*
	* Throws a CNetworkException on failure.
	*/
	u_long GetIPFromAddress (const std::string & sHost);

	/**
	* Connects to a given address and port.
	*
	* @param[in] nAddress Address to connect to in network byte order.
	* @param[in] nPort Port to connect to at nAddress in network byte order.
	* 
	* @return Newly connected socket on success.  On fail, returns INVALID_SOCKET.
	*/
		
	SOCKET ConnectToSocket(u_long nAddress, u_short nPort);

	SOCKET mSocket;

	int nLastPort;
	bool bDoPortStepping;

};

#endif  //NETWORKHANDLER_H